package com.hamu.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hamu.mapper.MediaMapper;
import com.hamu.pojo.Article;
import com.hamu.pojo.Media;
import com.hamu.pojo.PageBean;
import com.hamu.service.MediaService;
import com.hamu.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class MediaServiceImpl implements MediaService {
    @Autowired
    private MediaMapper mediaMapper;

    @Override
    public void add(Media media) {
        //补充属性值
        media.setCreateTime(LocalDateTime.now());
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer)map.get("id");
        media.setCreateUser(userId);
        mediaMapper.add(media);
    }

    @Override
    public void delete(Integer id) {
        mediaMapper.delete(id);
    }

    @Override
    public Media findById(Integer id) {
        return mediaMapper.findById(id);
    }

    @Override
    public PageBean<Media> list(Integer pageNum, Integer pageSize){
        //创建PageBean对象
        PageBean<Media> pb = new PageBean<>();
        //开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);
        List<Media> img = mediaMapper.list();
        Page<Media> p =(Page<Media>) img;
        //把数据填充到PageBean对象
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public PageBean<Media> searchList(Integer pageNum, Integer pageSize, String query) {
        PageBean<Media> pb=new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Media> medias = mediaMapper.searchMedias(query);
        Page<Media> p = (Page<Media>) medias;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void update(Media media) {
        mediaMapper.update(media);
    }
}
